package Wormish.agiletre.se;

import Wormish.agiletre.se.Math.Vec2f;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;


public class Animation
{	
	public int FrameWidth;
	public float FrameLength = 0.1f; // Time to display each frame in seconds
	
	public Bitmap SpriteSheet;
	public int NumberOfFrames = 0;
	public int CurrentFrame = 0;
	float timer = 0;
	
	public boolean Reverse = false;
	
	public boolean Loop = true;
	
	public Animation(Bitmap spriteSheet, int numberOfFrames, float frameLength, boolean mirror)
	{
		if(mirror)
		{
	        Matrix matrix = new Matrix();
	        matrix.preScale(-1, 1);
	        spriteSheet = Bitmap.createBitmap(spriteSheet, 0, 0, spriteSheet.getWidth(), spriteSheet.getHeight(), matrix, false);
		}
		
		SpriteSheet = spriteSheet;
		NumberOfFrames = numberOfFrames;
		FrameLength = frameLength;
		FrameWidth = spriteSheet.getWidth() / numberOfFrames;
	}
	
	public void Update(float dt)
	{
		timer += dt;
		
		if(timer >= FrameLength)
		{
			if(Reverse)
			{
				CurrentFrame--;
				
				if(CurrentFrame < 0)
				{
					if(Loop)
					{
						CurrentFrame = NumberOfFrames - 1;
					}
					else
					{
						CurrentFrame = 0;
					}
				}
			}
			else
			{
				CurrentFrame++;
				
				if(CurrentFrame > NumberOfFrames - 1)
				{
					if(Loop)
					{
						CurrentFrame = 0;
					}
					else
					{
						CurrentFrame = NumberOfFrames - 1;
					}
				}
			}
			
			timer = 0;
		}
	}
	
	public void Draw(Canvas canvas, Vec2f position)
	{
		int x = CurrentFrame * FrameWidth;
		//int y = 0;
		int height = SpriteSheet.getHeight();
		int width = x + FrameWidth;
		
		Vec2f origin = new Vec2f(FrameWidth / 2, height);
		
		Rect frame = new Rect(x, 0, width, height);
		Rect destination = new Rect((int)(position.getX() - origin.getX()), (int)(position.getY() - origin.getY()), (int)(position.getX() + FrameWidth - origin.getX()), (int)(position.getY() + height - origin.getY()));
		canvas.drawBitmap(SpriteSheet, frame, destination, null);
	}
}
